<template>
  <view class="login-page">
    <view class="login-container">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image src="../../static/images/logo.png" class="logo" mode="aspectFit" />
        <text class="app-name">优课乐陵</text>
        <text class="app-desc">发现身边的优质课程</text>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <view class="welcome-text">
          <text class="welcome-title">欢迎使用优课乐陵</text>
          <text class="welcome-desc">请使用微信授权登录</text>
        </view>

        <!-- 微信登录按钮 -->
        <button 
          class="wx-login-btn" 
          open-type="getUserInfo" 
          @getuserinfo="onGetUserInfo"
          :loading="loginLoading"
        >
          <at-icon value="wechat" size="20" color="#fff"></at-icon>
          <text class="btn-text">微信授权登录</text>
        </button>

        <!-- 测试登录按钮（开发环境） -->
        <button 
          class="test-login-btn" 
          @click="testLogin"
          :loading="loginLoading"
          v-if="isDev"
        >
          <text class="btn-text">测试登录 (ID: 1)</text>
        </button>

        <!-- 手机号登录 -->
        <view class="phone-login" v-if="showPhoneLogin">
          <view class="input-group">
            <at-input
              v-model="phoneNumber"
              type="phone"
              placeholder="请输入手机号"
              :border="false"
              class="phone-input"
            />
          </view>
          
          <view class="input-group">
            <at-input
              v-model="smsCode"
              type="text"
              placeholder="请输入验证码"
              :border="false"
              class="code-input"
            >
              <template #action>
                <button 
                  class="send-code-btn"
                  @click="sendSmsCode"
                  :disabled="codeSending || countdown > 0"
                >
                  {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
                </button>
              </template>
            </at-input>
          </view>

          <button 
            class="phone-login-btn"
            @click="phoneLogin"
            :loading="loginLoading"
            :disabled="!phoneNumber || !smsCode"
          >
            手机号登录
          </button>
        </view>

        <!-- 切换登录方式 -->
        <view class="switch-login" @click="toggleLoginType">
          <text class="switch-text">
            {{ showPhoneLogin ? '使用微信登录' : '使用手机号登录' }}
          </text>
        </view>
      </view>

      <!-- 协议条款 -->
      <view class="agreement">
        <text class="agreement-text">
          登录即表示同意
          <text class="agreement-link" @click="showAgreement('user')">《用户协议》</text>
          和
          <text class="agreement-link" @click="showAgreement('privacy')">《隐私政策》</text>
        </text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import userApi from '@/api/user'
import { showLoading, hideLoading, showError, showSuccess } from '@/utils'

// 响应式数据
const loginLoading = ref(false)
const showPhoneLogin = ref(false)
const phoneNumber = ref('')
const smsCode = ref('')
const codeSending = ref(false)
const countdown = ref(0)
const isDev = process.env.NODE_ENV === 'development'

// 页面加载
onMounted(() => {
  // 检查是否已登录
  checkLoginStatus()
})

// 检查登录状态
const checkLoginStatus = () => {
  const token = Taro.getStorageSync('token')
  if (token) {
    // 已登录，跳转到首页
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
}

// 微信授权登录
const onGetUserInfo = async (e) => {
  if (e.detail.errMsg === 'getUserInfo:ok') {
    try {
      loginLoading.value = true
      showLoading('登录中...')
      
      // 获取微信登录code
      const loginRes = await Taro.login()
      if (loginRes.code) {
        // 调用后端登录接口
        const result = await userApi.wxLogin(loginRes.code)
        
        if (result.code === 200) {
          // 保存token和用户信息
          Taro.setStorageSync('token', result.data.token)
          Taro.setStorageSync('userInfo', result.data.userInfo)
          
          showSuccess('登录成功')
          
          // 跳转到首页
          setTimeout(() => {
            Taro.reLaunch({
              url: '/pages/index/index'
            })
          }, 1500)
        } else {
          showError(result.msg || '登录失败')
        }
      } else {
        showError('获取微信授权失败')
      }
    } catch (error) {
      console.error('微信登录失败:', error)
      showError('登录失败，请重试')
    } finally {
      loginLoading.value = false
      hideLoading()
    }
  } else {
    showError('需要授权才能使用')
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!phoneNumber.value) {
    showError('请输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(phoneNumber.value)) {
    showError('请输入正确的手机号')
    return
  }
  
  try {
    codeSending.value = true
    await userApi.sendSmsCode(phoneNumber.value)
    
    showSuccess('验证码已发送')
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    console.error('发送验证码失败:', error)
    showError('发送验证码失败')
  } finally {
    codeSending.value = false
  }
}

// 手机号登录
const phoneLogin = async () => {
  if (!phoneNumber.value || !smsCode.value) {
    showError('请输入手机号和验证码')
    return
  }
  
  try {
    loginLoading.value = true
    showLoading('登录中...')
    
    const result = await userApi.bindPhone(phoneNumber.value, smsCode.value)
    
    if (result.code === 200) {
      // 保存token和用户信息
      Taro.setStorageSync('token', result.data.token)
      Taro.setStorageSync('userInfo', result.data.userInfo)
      
      showSuccess('登录成功')
      
      // 跳转到首页
      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
    } else {
      showError(result.msg || '登录失败')
    }
  } catch (error) {
    console.error('手机号登录失败:', error)
    showError('登录失败，请重试')
  } finally {
    loginLoading.value = false
    hideLoading()
  }
}

// 测试登录（开发环境）
const testLogin = async () => {
  try {
    loginLoading.value = true
    showLoading('登录中...')
    
    const result = await userApi.testLogin(1)
    
    if (result.code === 200) {
      // 保存token
      Taro.setStorageSync('token', result.data.token)
      
      showSuccess('测试登录成功')
      
      // 跳转到首页
      setTimeout(() => {
        Taro.reLaunch({
          url: '/pages/index/index'
        })
      }, 1500)
    } else {
      showError(result.msg || '测试登录失败')
    }
  } catch (error) {
    console.error('测试登录失败:', error)
    showError('测试登录失败，请重试')
  } finally {
    loginLoading.value = false
    hideLoading()
  }
}

// 切换登录方式
const toggleLoginType = () => {
  showPhoneLogin.value = !showPhoneLogin.value
  // 清空表单数据
  phoneNumber.value = ''
  smsCode.value = ''
  countdown.value = 0
}

// 显示协议
const showAgreement = (type) => {
  const url = type === 'user' ? '/pages/agreement/user' : '/pages/agreement/privacy'
  Taro.navigateTo({ url })
}
</script>

<style lang="less">
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #3478F6 0%, #5B9BF8 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-container {
  width: 100%;
  max-width: 600px;
}

.logo-section {
  text-align: center;
  margin-bottom: 80px;
  
  .logo {
    width: 120px;
    height: 120px;
    margin-bottom: 24px;
  }
  
  .app-name {
    display: block;
    font-size: 48px;
    font-weight: bold;
    color: white;
    margin-bottom: 16px;
  }
  
  .app-desc {
    display: block;
    font-size: 28px;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  background: white;
  border-radius: 24px;
  padding: 48px 40px;
  margin-bottom: 40px;
  
  .welcome-text {
    text-align: center;
    margin-bottom: 48px;
    
    .welcome-title {
      display: block;
      font-size: 36px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
    }
    
    .welcome-desc {
      display: block;
      font-size: 28px;
      color: #666;
    }
  }
  
  .wx-login-btn {
    width: 100%;
    height: 88px;
    background: #07C160;
    color: white;
    border: none;
    border-radius: 44px;
    font-size: 32px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32px;
    
    .btn-text {
      margin-left: 16px;
    }
    
    &:disabled {
      opacity: 0.6;
    }
  }
  
  .test-login-btn {
    width: 100%;
    height: 88px;
    background: #FF6B35;
    color: white;
    border: none;
    border-radius: 44px;
    font-size: 32px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32px;
    
    .btn-text {
      margin-left: 16px;
    }
    
    &:disabled {
      opacity: 0.6;
    }
  }
  
  .phone-login {
    margin-top: 32px;
    
    .input-group {
      margin-bottom: 32px;
      
      .phone-input, .code-input {
        background: #f8f9fa;
        border-radius: 12px;
        padding: 0 24px;
        height: 88px;
        
        :deep(.at-input__input) {
          font-size: 28px;
        }
      }
      
      .send-code-btn {
        background: #3478F6;
        color: white;
        border: none;
        border-radius: 8px;
        padding: 12px 24px;
        font-size: 24px;
        
        &:disabled {
          opacity: 0.6;
        }
      }
    }
    
    .phone-login-btn {
      width: 100%;
      height: 88px;
      background: #3478F6;
      color: white;
      border: none;
      border-radius: 44px;
      font-size: 32px;
      font-weight: 500;
      
      &:disabled {
        opacity: 0.6;
      }
    }
  }
  
  .switch-login {
    text-align: center;
    margin-top: 32px;
    
    .switch-text {
      color: #3478F6;
      font-size: 28px;
    }
  }
}

.agreement {
  text-align: center;
  
  .agreement-text {
    font-size: 24px;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.5;
    
    .agreement-link {
      color: white;
      text-decoration: underline;
    }
  }
}
</style>